<template>
    <div class="userInfo-page-container">
        <el-row :gutter="0">
            <el-col :offset="3" :span="3" class="clearfix">
                <div id="about-left-part" class="about-left-part">
                    <div style="height: 300px;">
                        <el-tabs :value="tabActive" v-model="tabActive" style="height: 200px;" tab-position="left"
                                 @tab-click="tabItemClick">
                            <el-tab-pane label="用户信息" name="1"></el-tab-pane>
                            <el-tab-pane label="我们的使命" name="2"></el-tab-pane>
                            <el-tab-pane label="联系我们" name="3"></el-tab-pane>
                            <el-tab-pane label="我们的愿景" name="4"></el-tab-pane>
                        </el-tabs>
                    </div>
                </div>
            </el-col>
            <el-col :span="18">
                <div id="about-right-part" class="about-right-part">
                    <div class="user-info-header-bg">
                        <img :src="userInfo.avatar" alt="">
                    </div>

                    <div class="about-item">
                        <h1 id="1">用户信息</h1>
                        <div class="avatar-username">
                            <img :src="userInfo.avatar" alt="">
                            <span>{{ userInfo.userName }}</span>
                        </div>
                        <div class="info-item">
                            <span>角色:</span>
                            <el-tag type="success" v-if="userInfo.roles === 'role_normal'" size="mini">
                                用户
                            </el-tag>
                            <el-tag type="danger" v-else size="mini">
                                管理员
                            </el-tag>
                        </div>
                        <div class="info-item reg-time">
                            <span>注册时间:</span>
                            {{ userInfo.createTime  | formatDate('yyyy-MM-dd hh:mm') }}
                        </div>
                        <div class="user-sign info-item">
                            <el-row :gutter="10">
                                <el-col :span="2">
                                    <span>签名:</span>
                                </el-col>
                                <el-col :span="18">
                                    <span>{{ userInfo.sign }}</span>
                                </el-col>
                                <el-col :span="4">
                                    <div v-if="this.$route.params.id === $store.state.currentUserId"
                                         class="edit-user-info-active">
                                        <el-button size="mini"
                                                   type="primary"
                                                   @click="editSign">编辑
                                        </el-button>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                    <hr/>
                    <div class="about-item">
                        <h1 id="2">我们的使命</h1>
                        <p>阳光沙通创立于2014年11月22日.那是一个阳光明量的下午。韩弯的电影《后会无期》里面有一句
                            可以在这里学习，写博客.写笔记.分享经验.提问题,分享链接。你可以遇到志同道合的人。收获知识。经验与同性朋友。</p>
                    </div>
                </div>
            </el-col>
        </el-row>


        <!--            更新自己信息的弹窗-->
        <el-dialog
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :fullscreen="false"
            :visible="userEditorDialogVisible"
            title="更新信息"
            width="45%"
            @close="resetData">
            <div class="looper-editor-box">
                <el-form :ref="changeUserInfoForm"
                         :model="userInfo"
                         :rules="rules"
                         label-width="80px">

                    <el-form-item label="用户名" prop="userName">
                        <el-input v-model="userInfo.userName" placeholder="用户名"></el-input>
                    </el-form-item>

                    <el-form-item label="验证码" :required="true" prop="captcha">
                        <el-input v-model="userInfo.captcha" placeholder="输入验证码"></el-input>

                        <img :src="captchaPath" alt="获取验证码失败"
                             @click="updateCaptchaCode"
                             class="captcha-code-cursor">
                    </el-form-item>

                    <el-form-item label="邮箱地址" prop="email">
                        <el-input v-model="userInfo.email" placeholder="邮箱地址"></el-input>
                    </el-form-item>

                    <el-form-item v-if="userInfo.email !== oldEmail" label="验证码" prop="verifyCode">
                        <el-row :gutter="10">
                            <el-col :span="11">
                                <el-input v-model="userInfo.verifyCode" placeholder="输入邮箱验证码"></el-input>
                            </el-col>
                            <el-col :span="11">
                                <el-button type="primary" size="mini" @click="sendEmailVerifyCode"
                                           v-text="sendVerifyBtnText" :disabled="sendVerifyBtnText !== '发送验证码'">
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>

                    <el-form-item label="签名" prop="sign">
                        <el-input v-model="userInfo.sign" placeholder="签名"></el-input>
                    </el-form-item>

                    <el-form-item label="头像上传" prop="avatar">
                        <el-upload
                            class="avatar-uploader"
                            action="/admin/image/avatar"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="this.userInfo.avatar!==''" :src="this.userInfo.avatar" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="userEditorDialogVisible = false">取 消</el-button>
                <el-button type="primary"
                           @click="updateUser">更新</el-button>
                </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    checkCaptchaCode,
    checkEmailUnique,
    checkUserNameUnique,
    getUserInfo,
    putUser,
    sendEmailVerifyCode
} from "assets/api/userApi";
import {success_code} from "assets/utils/LRConstant";

export default {
    components: {},
    data() {
        return {
            changeUserInfoForm: 'changeUserInfoForm',
            userEditorDialogVisible: false,
            sendVerifyBtnText: "发送验证码",
            oldEmail: '',
            userInfo: {
                id: "",
                userName: "",
                password: "",
                roles: "",
                avatar: "",
                email: "",
                sign: "",
                state: "",
                regIp: "",
                loginIp: "",
                createTime: '',
                verifyCode: '',
                captcha: ''
            },
            rules: {
                userName: [
                    {required: true, message: '用户名不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkUserName, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '邮箱不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkEmail, trigger: 'blur'}
                ],
                verifyCode: [
                    {validator: this.checkVerifyCode, trigger: 'blur'}
                ],
                captcha: [
                    {required: true, message: '验证码不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkCaptchaCode, trigger: 'blur'}
                ],
            },
            tabActive: '1',
            contentHeader: [],
            isClickLeftTab: false,
            show: false,
            headers: {
                smail: '*_~'
            },
            captchaPath: '',
            imageUrl: '' // the date base 64 url of created image
        };
    },
    async asyncData({params}) {
        let userInfoData = await getUserInfo(params.id);
        return {
            userInfo: userInfoData.data,
        }
    },
    mounted() {
        // init variable
        this.oldEmail = this.userInfo.email;
        let rightBox = document.getElementById("about-right-part");

        let h1List = rightBox.querySelectorAll('h1');

        h1List.forEach((item) => {

            this.contentHeader.push({
                offsetTop: item.offsetTop,
                id: item.id
            });
        })

        // init Listener
        window.addEventListener("scroll", this.onWindowScroll)
        // window.addEventListener("resize", this.onWindowScroll);
        window.onresize = this.onWindowScroll();
    },
    methods: {
        checkCaptchaCode(rule, value, callback) {
            checkCaptchaCode(value).then((result) => {
                if (result.code === success_code) {
                    callback();
                } else {
                    callback(new Error("验证码不正确"));
                }
            })
        },
        resetData() {
            this.$refs[this.changeUserInfoForm].resetFields();
        },
        tabItemClick(tab) {
            // init variable
            let bolgHeader = document.getElementById(tab.name);

            // change flag
            this.isClickLeftTab = true;

            // change ui
            if (bolgHeader != null) {
                document.documentElement.scrollTo({
                    top: bolgHeader.offsetTop,
                    behavior: "auto",
                });
            }
        },
        onWindowScroll: function () {
            // init variable
            let dy = document.documentElement.scrollTop;

            // 处理右边滑动左边的激活状态
            if (this.isClickLeftTab === false) {
                for (let i = 0; i < this.contentHeader.length; i++) {
                    let first = this.contentHeader[i];
                    let second = this.contentHeader[i + 1];

                    if (dy >= first.offsetTop && dy <= second.offsetTop) {
                        this.tabActive = first.id;
                        break;
                    }
                }
            } else {
                this.isClickLeftTab = false;
            }
        },
        editSign() {
            this.userEditorDialogVisible = true;
            this.updateCaptchaCode();
        },
        updateUser() {
            this.$refs.changeUserInfoForm.validate((value) => {
                if (value) {

                    let user = {
                        id: this.userInfo.id,
                        userName: this.userInfo.userName,
                        email: this.userInfo.email,
                        sign: this.userInfo.sign,
                        userAvatar: this.userInfo.avatar
                    }
                    putUser(user).then((result => {
                        if (result.code = success_code) {
                            // change ui
                            this.$message.success('更新成功');

                            // change flag and cache
                            this.userEditorDialogVisible = false;

                            getUserInfo(params.id).then((result) => {
                                if (result.code = success_code) {
                                    this.userInfo = result.data;
                                }
                            });
                        } else {
                            this.$message.error('更新失败');
                        }
                    }));
                } else {
                    this.$message.warning('校验不通过');
                }
            });
        },
        handleAvatarSuccess(res) {
            // console.log(res);
            this.userInfo.avatar = '/portal/image/' + res.data.path;
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 6;

            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 6MB!');
            }
            return isLt2M;
        },
        sendEmailVerifyCode() {
            this.$refs[this.changeUserInfoForm].clearValidate();

            this.$refs.changeUserInfoForm.validateField("email", (val) => {
                // console.log(val);

                if (!val) {
                    sendEmailVerifyCode(this.LRUser.email).then((result) => {
                        if (result.code === success_code) {
                            // change ui
                            let clickBtnInterval = 15;

                            let interval = setInterval(() => {
                                clickBtnInterval--;
                                if (clickBtnInterval <= 0) {
                                    this.sendVerifyBtnText = "发送验证码";
                                    clearInterval(interval)
                                    return;
                                }

                                this.sendVerifyBtnText = "重新发送(" + clickBtnInterval + ")";
                            }, 1000);

                            this.$message.success("发送验证码成功")
                        } else {
                            this.$message.error("发送验证码失败 cause by:" + result.message);
                        }
                    });
                } else {
                    this.$message.warning("确认你的邮箱是否合法");
                }
            });
        },
        updateCaptchaCode: function () {
            // 为节约资源 一直使用一个时间戳
            // 只有单人系统才能这么做
            // 但是会导致url 一直一样， vue 不会修改界面
            // 所以添加了一个随机参数 来改变url
            this.captchaPath = "/user/captcha?random=" + Date.parse(new Date());
        },
        checkEmail(rule, value, callback) {
            if (value === '') {
                callback(new Error('邮箱不能为空'));
            } else {
                const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

                if (!reg.test(value)) {
                    callback(new Error("邮箱格式不正确"));
                }

                checkEmailUnique(value, this.userInfo.id).then((result) => {
                    if (result.code === 4043) {
                        callback();
                    } else {
                        callback(new Error(result.message));
                    }
                });
            }
        },
        checkVerifyCode(rule, value, callback) {
            if (this.userInfo.email !== this.oldEmail) {
                if (value === '') {
                    callback(new Error('邮箱验证码不能为空'));
                } else {
                    callback();
                }
            } else {
                callback();
            }

        },
        checkUserName(rule, value, callback) {
            if (value === '') {
                callback(new Error('用户名不能为空'));
            } else {
                checkUserNameUnique(value, this.userInfo.id).then((result) => {
                    if (result.code === 4044) {
                        callback();
                    } else {
                        callback(new Error(result.message));
                    }
                });
            }
        },
    },
    beforeDestroy() {
        window.removeEventListener('scroll', this.onWindowScroll)
    }
}
</script>

<style scoped>
.userInfo-page-container {
    background-color: white;
    margin-top: 20px;
    border-radius: 4px;
}

.about-item h1 {
    margin-bottom: 10px;
}

.about-item {
    margin-bottom: 50px;
}

.avatar-username img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    vertical-align: middle;
}

.avatar-username span {
    margin-left: 20px;
    font-size: 18px;
    font-weight: 600;
    color: gray;
}

.user-info-header-bg img {
    width: 100%;
    height: 200px;
    filter: blur();
    border-radius: 4px;
}

.info-item span {
    font-size: 16px;
    font-weight: 600;
    margin-right: 20px;
}

.info-item {
    height: 28px;
    line-height: 28px;
    margin: 10px 0;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>